// ==UserScript==
// @name        SharePoint 2010/2013 Dev Tools
// @namespace   TiagoDuarte
// @description Adds new buttons near the ribbon for common useful actions
// @version     Version 0.6
// @grant       none
// @match       http://*.mydomain/*
////enable the line below to support sites without jquery (ootb). but may cause problems with sites that have jquery already
//// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// ==/UserScript==

// a function that loads jQuery and calls a callback function when jQuery has finished loading
function addJQuery(callback) {
  var script = document.createElement("script");
  script.setAttribute("src", "//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js");
  script.addEventListener('load', function() {
    var script = document.createElement("script");
    script.textContent = "window.jQ=jQuery.noConflict(true);(" + callback.toString() + ")();";
    document.body.appendChild(script);
  }, false);
  document.body.appendChild(script);
}


function main() {
    // Note, jQ replaces $ to avoid conflicts.
  
    
    
//associate buttons with functions and icons
function AddDevToolsButton(id, btn_title, img_y, img_x, callback)
{
  //dialogs only
  if ((id == 'getIframeLink') && (window.location.href.indexOf('IsDlg') > -1))
  {
    var rootElement = '.ms-cui-topBar2';
  } 
  else
  {
    var rootElement = '#siteactiontd';
  }
  //add new element to DOM

  var toAdd = '<span class="s4-breadcrumb-anchor" id="' + id + '"><span class="ms-cui-img-16by16 ms-cui-img-cont-float" unselectable="on"><img alt="' + btn_title + '" title="' + btn_title + '" style="top: ' + img_y + '; left: ' + img_x + ';" src="/_layouts/1033/images/formatmap16x16.png" alt="" unselectable="on" /></span></span>';
  $(rootElement).append(toAdd);
  //bind callback to new element
  eval(callback) ();
}

//command functions
function CmdExplorerView()
{
  $('#customOpenInExplorer').click(function () {
    var urlToOpen = 'file://' + (location.hostname + (location.port ? ':' + location.port : '') + location.pathname.substring(0, location.pathname.lastIndexOf('/')).replace('/Forms', ''));
    window.prompt('Here is the path for file explorer', urlToOpen);
  });
}
function CmdWebTemplateID()
{
  $('#getWebTemplateID').click(function () {
    window.prompt('Here is this site Template ID', g_wsaSiteTemplateId);
  });
}
function CmdSaveTemplate()
{
  $('#saveSiteAsTemplate').click(function () {
    var currentUrl = (window.location.href.substring(0, window.location.href.lastIndexOf('/')))
    currentUrl = currentUrl.substring(0, currentUrl.lastIndexOf('/'));
    window.location.href = currentUrl + "/_layouts/savetmpl.aspx";
  });
}
function CmdRefreshPage()
{
  $('#refreshThisPage').click(function () {
    window.location.href = window.location.href.replace('#', '');
  });
}
function CmdSignInAsAnotherUser()
{
  $('#signInAsAnotherUser').click(function () {
    //navigate to http://{YourSharePointSiteURL}/_layouts/CloseConnection.aspx?Loginasdifferentuser=true 
	
	//2010
	var signInUrl = "/_layouts/closeConnection.aspx?loginasanotheruser=true";
	//2013 - can be the same as 2010
	//var signInUrl = "/_layouts/15/closeConnection.aspx?loginasanotheruser=true";
	
    var sourceUrl = window.location.href;
    var currentUrl = (window.location.href.substring(0, window.location.href.lastIndexOf('/')));
	//non-root site - divide further
	if(currentUrl.replace("http://", "").indexOf('/') !== -1)
	{
		currentUrl = currentUrl.substring(0, currentUrl.lastIndexOf('/'));
	}
    var navigateUrl = currentUrl + signInUrl + "?Source=" + encodeURIComponent(sourceUrl);
    //alert(navigateUrl);
    window.location.href = navigateUrl;       
  });
}
function CmdIframeLink()
{
  $('#getIframeLink').click(function () {
    
    var iframeUrl = "not found";
    
    //url is the page itself
    if(window.location.href.indexOf('IsDlg') == -1)
      {
       iframeUrl = window.location.href.replace('#', '');
      }
    else
      { 
        //url is the iframe's url (not the form's url, which is a redirect)
        
        //iframe = _layouts/listform
        //form = upload.aspx (redirected from listform)
        
        //get parent window while inside an iframe
        var parentWindow = window.parent.document;
        var iframes = $('iframe', parentWindow);
           
        for (var i = 0; i < iframes.length; i++)
        {
          if ((iframes[i] != null) && (iframes[i].src != null))
          {
            if (iframes[i].src.indexOf('http://') > - 1)
            {
              iframeUrl = iframes[i].src.replace("&IsDlg=1", "");
            }
          }
        }
      }    
    window.prompt('Here is the URL for this page/frame', iframeUrl);
  });
}


    
    
    //bindings
    $(document).ready(function () {
        //AddDevToolsButton("id_of_new_element", "button title", "vertical_axis", ""horizontal_axix, button_callback);
        //user http://getspritexy.com/ to find location within formatmap16x16.png
        AddDevToolsButton('customOpenInExplorer', 'Open with Explorer', '-112px', '-176px', CmdExplorerView);
        AddDevToolsButton('getWebTemplateID', 'Get Web Template ID', '-48px', '-80px', CmdWebTemplateID);
        AddDevToolsButton('refreshThisPage', 'Refresh Page (no resubmit)', '-240px', '-192px', CmdRefreshPage);
        AddDevToolsButton('getIframeLink', 'Get a link for this page', '-160px', '-224px', CmdIframeLink);
        AddDevToolsButton('signInAsAnotherUser', 'Sign in as a different user', '-160px', '-112px', CmdSignInAsAnotherUser);
        //AddDevToolsButton('saveSiteAsTemplate', 'Save this site as a template', '-112px', '0px', CmdSaveTemplate);
    });
    
}


addJQuery(main);
